package com.touchfired.common.core.listener.impl;

import com.touchfired.common.constants.ClientInfo;
import com.touchfired.common.constants.GameRule;
import com.touchfired.common.constants.RoomInfo;
import com.touchfired.common.context.ServerContext;
import com.touchfired.common.core.callback.Callback;
import com.touchfired.common.core.event.impl.RoomCreateEvent;
import com.touchfired.common.core.listener.BaseListener;
import com.touchfired.common.params.CreateRoomParams;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 创建房间 监听器
 *
 * @author 幸佳俊
 */
@Component
public class RoomCreateListener extends BaseListener<RoomCreateEvent> {

    private final ServerContext serverContext;

    public RoomCreateListener(ServerContext serverContext) {
        this.serverContext = serverContext;
    }

    @Override
    public void onEvent(RoomCreateEvent roomCreateEvent, Callback callback) {
        ClientInfo clientInfo = roomCreateEvent.getClientInfo();
        CreateRoomParams roomParams = roomCreateEvent.getRoomParams();

        RoomInfo roomInfo = new RoomInfo();
        roomInfo.setCreateClientLongId(clientInfo.getLongId());
        roomInfo.setCreateTime(LocalDateTime.now());
        roomInfo.setRoomName(roomParams.getRoomName());
        roomInfo.getRoomClientLongIds().add(clientInfo.getLongId());
        roomInfo.setGameRule(new GameRule(roomParams.getPlayerNum(), roomParams.getSpyerNum()));

        serverContext.addRoomInfo(roomInfo);
        serverContext.updateClientInfo(clientInfo.setRoomId(roomInfo.getRoomId()));

        callback.call(roomInfo);
    }

}
